package com.oom;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @Author: tgy
 * @Date: 2020-08-05 10:55
 */

/**
 *
 * -XX:MetaspaceSize=10M -XX:MaxMetaspaceSize=10M -XX:+PrintGCDetails
 *
 * Exception in thread "main" java.lang.OutOfMemoryError: Metaspace
 * 	at org.springframework.cglib.core.ReflectUtils.defineClass(ReflectUtils.java:538)
 * 	at org.springframework.cglib.core.AbstractClassGenerator.generate(AbstractClassGenerator.java:363)
 * 	at org.springframework.cglib.proxy.Enhancer.generate(Enhancer.java:585)
 * 	at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData.get(AbstractClassGenerator.java:131)
 * 	at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:319)
 * 	at org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:572)
 * 	at org.springframework.cglib.proxy.Enhancer.create(Enhancer.java:387)
 * 	at com.oom.MetaSpace.main(MetaSpace.java:53)
 */

class CGLIBClass{

    @Override
    public String toString() {
        return super.toString();
    }
}

public class MetaSpace {

    static class Inner{


    }

    private static List<String> cons = new ArrayList<>();

    public static void main(String[] args) {

//        Random random = new Random();
//
//        while (true){
//
//            cons.add(random.toString().intern());
//        }
        while (true){

            Enhancer enhancer = new Enhancer();

            enhancer.setSuperclass(CGLIBClass.class);

            enhancer.setUseCache(false);

            enhancer.setCallback(new MethodInterceptor() {
                @Override
                public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

                    return method.invoke(o,objects);
                }
            });

            Object o = enhancer.create();

            System.out.println(o);
        }

    }
}
